package com.android.lovely.admob

import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Lifecycle
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.FullScreenContentCallback
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.rewarded.RewardedAd
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback
import com.kotlin.extensions.appContext
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume


suspend fun loadReward(id: String): RewardedAd? = suspendCancellableCoroutine { callback ->
    RewardedAd.load(appContext, id, AdRequest.Builder().build(), object : RewardedAdLoadCallback() {
        override fun onAdFailedToLoad(adError: LoadAdError) {
            callback.resume(null)
        }

        override fun onAdLoaded(ad: RewardedAd) {
            callback.resume(ad)
        }
    })
}

fun FragmentActivity.showReword(ad: Ad, onDismiss: (Boolean) -> Unit) {
    var hasReward = false
    if (!ad.hasCache() && lifecycle.currentState != Lifecycle.State.RESUMED) {
        onDismiss.invoke(false)
        return
    }
    val cache = ad.getCache()

    if (cache == null) {
        onDismiss.invoke(false)
        return
    }
    cache.fullScreenContentCallback = object : FullScreenContentCallback() {

        override fun onAdDismissedFullScreenContent() {
            onDismiss.invoke(hasReward)
        }
    }
    cache.show(this) { hasReward = true }
    if (ad != Ad.DailySign) {
        ad.load()
    }

}